<?php

namespace app\admin\controller;

use helper\JwtHelper;
use think\App;
use think\facade\Cache;
use think\facade\View;
use traits\controller\JumpTraits;
use traits\controller\QueryTraits;

/**
 * 控制器基础类
 */
abstract class Base
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var App
     */
    protected $app;

    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];

    /**
     * 登录信息
     */
    protected $loginInfo = [];

    protected $role_ids;
    /**
     * 不需登录方法
     * @var array
     */
    protected $noLogin = [];

    use JumpTraits;
    use QueryTraits;

    /**
     * 构造方法
     * Base constructor.
     * @throws \Exception
     */
    public function __construct()
    {

        $this->app       = app();
        $this->request   = $this->app->request;
        $this->loginInfo = $this->getLoginInfo();
        //View::assign('loginInfo', $this->loginInfo);
    }

    /**
     * 获取登录信息
     * @return array|null
     */
    protected function getLoginInfo()
    {

        $action = $this->request->action();
        if (in_array($action, $this->noLogin) || in_array('*', $this->noLogin)) {
            return $this->loginInfo;
        }
        $token = $this->request->header("authorization");

        JwtHelper::make()->verfiyToken($token);
        $info            = JwtHelper::make()->all();
        $system_token = cache::get('system_token-'.$info['data']['id']);
        if(!$system_token){
            $this->result('请登录', "LOGIN_ERROR", 0);
        }
        try {

            $this->loginInfo = $info['data'];
            $this->role_ids = explode(',',$info['data']['role_ids']);
        } catch (\Exception $e) {
            $this->result('登录超时', "LOGIN_ERROR", 0);

        }
        return $this->loginInfo;
    }

    /**
     * 验证数据
     * @access protected
     * @param array $data 数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array $message 提示信息
     * @param bool $batch 是否批量验证
     * @param bool $failException 是否批量验证
     * @return bool|true
     */
    protected function validate(array $data, $validate, array $message = [], $batch = false, $failException = true)
    {
        return validate($validate, $message, $batch, $failException)->check($data);
    }

}
